package com.hjlsoft.aftp.ins.handler;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.hjlsoft.aftp.config.AftpConfig;
import com.hjlsoft.aftp.data.DataMeta;
import com.hjlsoft.aftp.data.DataMetaStatusEnum;
import com.hjlsoft.aftp.data.DataStoreService;
import com.hjlsoft.aftp.ins.AftpResultCode;
import com.hjlsoft.aftp.network.Request;
import com.hjlsoft.aftp.network.Response;
import com.hjlsoft.aftp.token.Token;
import com.hjlsoft.aftp.token.TokenManager;

public class ResetInsHandle extends BaseInsHandle {

	private TokenManager tokenManager;
	
	private DataStoreService dataStoreService;
	
	@Override
	public void onInit(AftpConfig config, Map<String, Object> services) {
		tokenManager = (TokenManager)services.get("tokenManager");
		dataStoreService = (DataStoreService)services.get("dataStoreService");
	}

	public void execute(Request request, Response response) throws IOException {
		if (!assertLogin(request, response)) {
			return;
		}
		
		List<String> params = request.getParamList();
		if (params == null || params.size() < 1) {
			response.writeResultCodeEnd(AftpResultCode.INVLIDATE_INS_PARAM);
			return;
		}
		String tokenId = params.get(0);
		Token token = tokenManager.get(tokenId);
		if (token == null) {
			response.writeResultCodeEnd(AftpResultCode.INVALIDATE_TOKEN);
			return;
		}
		String username = this.getLoginUsername(request);
		if (!username.equals(token.getUsername())) {
			response.writeResultCodeEnd(AftpResultCode.TOKEN_NOT_BELONG_USER);
			return;
		}
		
		DataMeta dataMeta = dataStoreService.getDataMeta(tokenId);
		if (dataMeta == null) {
			response.writeResultCodeEnd(AftpResultCode.DATA_NOT_EXIST);
			return;
		}
		
		if (dataMeta.getStatus() == DataMetaStatusEnum.COMMITTED.getValue()) {
			response.writeResultCodeEnd(AftpResultCode.DATA_HAS_BEEN_COMMITTED);
			return;
		}
		
		
		dataStoreService.delete(tokenId);
		
		response.writeResultCodeEnd(AftpResultCode.SUCCESS);
	}

	public String getIns() {
		return "reset";
	}

}
